<template>
  <a-row :gutter="[8,8]">
    <a-col :span="19">
      <div id="container"/>
    </a-col>
    <a-col :span="5">
      <a-form :model="graphData">
        <a-form-item label="场景">
          <a-select v-model:value="graphData.graphId" placeholder="请选择数据" @change="onIdChange">
            <a-select-option
                v-for = "item in dropdownData.tableData"
                :key="item.graphId"
                :value = "item.graphId">
              {{ item.graphName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-button @click="loadGraph">读取</a-button>
        <a-button @click="loadPlcData">装载运行数据</a-button>
        <a-button @click="loadPlcDataInterval">读取运行数据</a-button>
        <a-button @click="stopPlcDataInterval">停止读取运行数据</a-button>

      </a-form>
    </a-col>
  </a-row>
</template>

<script lang="ts">
import {defineComponent, onMounted, onUnmounted, reactive, UnwrapRef} from "vue";
import {Graph, Shape, Node, Addon, Cell} from '@antv/x6';
import { addPd, findPdById, list, plcdatalist, plcdatalistByGraphId, findGraphById } from '@/api/equip'
import { RecycleOpt } from '@/utils/recycleOpt'
import { list as typeList } from '@/api/equiptype'
import { list as graphList } from '@/api/graph'


let tableData = [
  {
    graphId: "",
    sourceId: "",
    belongingType: "",
    backgroundUrl: "",
    graphName: "",
    stationId: "",
    subareaId: ""
  },
  // {
  //   id: 2,
  //   title: "补水箱2#",
  //   content: "hrz1-bsx-1",
  // },
  // {
  //   id: 3,
  //   title: "水表3#",
  //   content: "hrz1-sb-1",
  // },
]

interface FormDataModel {
  id: any;
  title: any;
  content: any;
}

interface EquipModel {
  id: number | null;
  equipNum: string;
  remark: string;
  typeId: number;
}

interface GraphModel {
  _id: string;
  cells: Array<any>;
  background: string;
}

interface EquipTypeModel {
  id: number | null;
  deviceType: string;
  otherDeviceAttrId: number | null;
  remark: string;
}

interface PlcdataModel {
  deviceCode: string;
  indicatorId: string;
  indicatorName: string;
  plcVariableValue: string;
}

interface GraphProcessModel {
  graphId: string;
  sourceId: string;
  belongingType: string;
  backgroundUrl: string;
  graphName: string;
  stationId: string;
  subareaId: string;
  tenantId: bigint;
  orgId: bigint;
}


export default defineComponent({
  setup() {
    let graph: Graph;
    let stencil: Addon.Stencil;
    let curCel: Cell | null;
    let graphId: string;
    const plcIntervals: number[] = [];
    let dnd;
    const equipNums: Array<string> = []
    const nodeMap: Map<string,Node<Node.Properties>> = new Map();
    //const bkgraphpath = 'hrz.png'
    const bkgraph = reactive({bkgraphpath:'hrz.png'})
    console.log('bkgraph',bkgraph.bkgraphpath)
    // 中间画布
    const buildGraph = (): void =>{
      graph = new Graph({
        container: document.getElementById('container') as HTMLElement,
        height: 600,
        background: {
          image: require(`./../../assets/${bkgraph.bkgraphpath}`) ,
          position: {
            x:0,
            y:0
          },
          size: {
            width: 1600,
            height: 600,
          }
        },
        resizing: {
          enabled: true,
        },
      });

      // const graphContent = localStorage.getItem("workmanshipGraph");
      // if(typeof graphContent === 'undefined' || graphContent == null || graphContent === '') {
      //   console.log("graphContent is null");
      // } else {
      //   graph.fromJSON(JSON.parse(graphContent));
      // }
    }


    // 表单数据定义
    const formData: UnwrapRef<FormDataModel> = reactive({
      id: null,
      title: null,
      content: null,
    });
    // 所有下拉数据
    const dropdownData: UnwrapRef<any> = reactive({
      tableData: [{
        graphId: "",
        graphName: "",
      }],
    });

    const graphData: UnwrapRef<GraphProcessModel> = reactive({
      graphId: "",
      sourceId: "",
      belongingType: "",
      backgroundUrl: "",
      graphName: "",
      stationId: "",
      subareaId: "",
      tenantId: 1n,
      orgId: 1n
    });

    // 初始化事件
    // const initEvent = () => {
    //   // graph.on('node:mousedown',({cell}) => {
    //   //   console.log('node:mousedown',cell);
    //   // });
    //   graph.on('cell:click', ({cell}) => {
    //     console.log(cell.getAttrs())
    //     console.log(cell.getData())
    //     // 将之前被选中的节点样式清除
    //     curCel?.attr('body/stroke', null)
    //     // 新的节点赋值
    //     curCel = cell
    //     // 新的节点边框样式设置为红色
    //     //curCel?.attr('body/stroke', "red")

    //     // 将cell data中Id进行赋值
    //     const type = cell.getData()?.type;
    //     console.log("==type=="+type);
    //     formData.id = cell.getData()?.id
    //     const queryData: EquipModel = {
    //       id: null,
    //       remark: '',
    //       equipNum: '',
    //       typeId: type
    //     }
        
    //     if(formData.id){
    //       // 模拟请求数据
    //       setTimeout(() => {
    //         list(queryData).then(res => {
    //           console.log('equip list',res)
    //           const { data } = res
    //           const { rows } = data
              
    //           tableData = rows.map((val: EquipModel, index: number, array: Array<EquipModel>)=>{
    //               console.log('dd1',index,val, array,)
                  
    //               return { id: val.id, title: val.remark, content: val.equipNum};
    //           });
    //           console.log('cell:click',tableData)
    //           dropdownData.tableData = tableData
    //           const tableDataRow = tableData.filter(item => item.id === formData.id)[0];
    //           formData.title = tableDataRow.title
    //           formData.content = tableDataRow.content
    //         })
    //       }, 100)
    //     } else {
    //       list(queryData).then(res => {
    //           console.log('equip list',res)
    //           const { data } = res
    //           const { rows } = data
              
    //           tableData = rows.map((val: EquipModel, index: number, array: Array<EquipModel>)=>{
    //               console.log('dd1',index,val, array,)
                  
    //               return { id: val.id, title: val.remark, content: val.equipNum};
    //           });
    //           console.log('cell:click',tableData)
    //           dropdownData.tableData = tableData
    //           formData.title = null
    //           formData.content = null
    //         })
    //     }
    //   });
    // }
    onMounted(() => {
      buildGraph();
      //initEvent();
      // 模拟请求数据
      setTimeout(()=>{
        console.log('fetch dropdown')
        graphList(graphData).then(res => {
          console.log('graph list',res)
          //const { data } = res
          const { data } = res.data
          
          tableData = data.map((val: GraphProcessModel, index: number, array: Array<GraphProcessModel>)=>{
              console.log('dd1',index,val, array,)
              
              return { graphId: val.graphId, graphName: val.graphName };
          });
          console.log(tableData)
          dropdownData.tableData = tableData
        })
        //dropdownData.tableData= tableData;
      },1000)

      //const opt : RecycleOpt = new RecycleOpt()
      //opt.operateCycle(() => { console.log('recycleopt')});

    })

    onUnmounted(() => {
      plcIntervals.forEach(item => {
        clearInterval(item)
      })
    })

    const onIdChange = () =>{
      console.log('onIdChange',tableData)
      // 模拟请求
      setTimeout(()=>{
        const tableDataRow = tableData.filter(item => item.graphId === graphData.graphId)[0];
        graphData.graphName = tableDataRow?.graphName;
        graphData.backgroundUrl = tableDataRow?.backgroundUrl;

        // curCel?.setData({
        //   id: formData.id,
        //   deviceCode: formData.content
        // })
        // curCel?.attr('label/text', formData.title)

      },100)
    }

    const toJson = () => {
      console.log(graph.toJSON())
      //localStorage.setItem("workmanshipGraph",JSON.stringify(graph.toJSON()));
      //bkgraph.bkgraphpath = 'image.png'
      //graph.drawBackground({ image: require(`./../../assets/${bkgraph.bkgraphpath}`) })
      //console.log(`${bkgraph.bkgraphpath}`)
      const data = { 
        _id: graphId, 
        background: bkgraph.bkgraphpath, 
        belongType: "1",
        graphName: "graph1",
        tenantId: "1",
        orgId: "1",
        ... graph.toJSON()
      }
      console.log('save',data)
      addPd(data).then(response => {
        const res: any = response.data
        console.log(res)
      })
    }

    const loadPlcData = () => {
      console.log('loadPlcData==',graph.getNodes())
      
      graph.getNodes().map((val: Node, index: number, array: Array<Node>) => {
        console.log('loadPlcData== nodedata', val.shape, val.data);
        if( val.shape === 'image') {
          if(val.data.deviceCode !== undefined && val.data.deviceCode !== '') {
            console.log('loadPlcData== nodedata not null', val.data);
            equipNums.push(val.data.deviceCode)

            const dataRect = new Shape.HTML({
                    x: val.getPosition().x +val.getSize().width,
                    y: val.getPosition().y,
                    width: 150,
                    height: 50,
                    attrs: { 
                      body: {
                        fill: '#2ECC71',
                        opacity: '0.5',
                        stroke: '2ECC71',
                        rx: 5,
                        ry: 5
                      },
                      label: {
                        text: '',
                        fill: '#333',
                        fontSize: 13,
                      },
                    },
                    data: {
                      deviceCode: val.data.deviceCode
                    }
                  })
            graph.addNode(dataRect)
            nodeMap.set(val.data.deviceCode, dataRect)
          }
        }
      });
      console.log('loadPlcData== equipNums',equipNums)
      //plcdatalist(equipNums).then(res => {
      graphData.tenantId = 1n
      graphData.orgId = 1n
      plcdatalistByGraphId(graphData).then(res => {
        console.log('plcdatalist',res)
        const  data: Array<PlcdataModel> = res.data.data
        console.log('loadPlcData== data',data)
        for(const item of data) {
          console.log('loadPlcData== item',item)
          const deviNode: Node<Node.Properties>|undefined = nodeMap.get(item.deviceCode);
          deviNode?.setAttrByPath("label/text", item.indicatorName+item.plcVariableValue+"\r\n"+"压力")
        }
        
      })
    }

    const loadPlcDataLoop = () => {
      //plcdatalist(equipNums).then(res => {
      graphData.tenantId = 1n
      graphData.orgId = 1n
      plcdatalistByGraphId(graphData).then(res => {
        console.log('plcdatalist',res)
        const  data: Array<PlcdataModel> = res.data.data
        console.log('loadPlcData== data',data)
        for(const item of data) {
          console.log('loadPlcData== item',item)
          const deviNode: Node<Node.Properties>|undefined = nodeMap.get(item.deviceCode);
          deviNode?.setAttrByPath("label/text", item.indicatorName+item.plcVariableValue+"\r\n"+"压力")
        }
        
      })
    }

    const loadPlcDataInterval = () => {
      const plcInterval: number = setInterval(() => {
                      loadPlcDataLoop()
                    }, 1000)
      plcIntervals.push(plcInterval)
    }

    const stopPlcDataInterval = ()=> {
      plcIntervals.forEach(item => {
        clearInterval(item)
      })
    }

    const loadGraph = () => {
      console.log('loadGraph === graphId', graphData.graphId)
      //findPdById(graphData.graphId).then(response => {
        findGraphById(graphData.graphId).then(response => {
        console.log('loadgraph',response)
        const res: GraphModel = response.data.data
        console.log('loadgraph res',res._id, res.cells)
        graphId = res._id;
        graph.fromJSON(res.cells)
        if(res.background !== '') {
          bkgraph.bkgraphpath = res.background
        } else {
          graph.clearBackground()
        }
        graph.updateBackground()
        
      })
    }
    return {
      formData,
      dropdownData,
      graphData,
      onIdChange,
      toJson,
      loadGraph,
      loadPlcData,
      loadPlcDataInterval,
      stopPlcDataInterval
    }
  }
})
</script>

<style scoped lang="less">

</style>
